// pages/category/category.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leftMenuList: [],
    rightDataList: [],
    currentIndex: 0,
    scrollTop: 0
  },
  cates: [],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let cates = wx.getStorageSync('cates');
    //当本地没有任何数据存贮的时候 进行获取数据
    if (!cates) {
      this.getClassify()
    } else {//本地存在缓存数据
      //判断数据是否过期,设置10s过期时间并且进行判断
      if ((+new Date() - cates.time) > 100000) {
        //当超时后，重新获取数据
        this.getClassify();
      } else {
        this.cates = cates.data;
        //获取左侧商品分类数据
        let leftMenuList = this.cates.map(item => item.cat_name);
        //获取右侧商品分类商品数据
        let rightDataList = this.cates[0].children;
        this.setData({
          leftMenuList,
          rightDataList
        })
      }
    }
  },

  //分类封装
  async getClassify() {
    const { data } = await wx.categoryApi.getCategories()
    console.log(data);
    this.cates = data.message;
    //将数据存储到本地存储
    wx.setStorageSync("cates", {
      time: +new Date(),
      data: this.cates
    })
    //获取左侧按钮内容
    let leftMenuList = this.cates.map(item => item.cat_name);
    //获取右侧商品分类列表
    let rightDataList = this.cates[0].children;
    this.setData({
      leftMenuList,
      rightDataList
    })
  },

  //左侧商品分类点击事件并更改样式
  onItemClick(e) {
    // console.log(e);
    let { index } = e.currentTarget.dataset;
    let rightDataList = this.cates[index].children;
    this.setData({
      rightDataList,
      currentIndex: index,
      scrollTop: 0
    })
  },
})